package cc.yugu.yhdw.webserver.service.basic;

import cc.yugu.yhdw.common.constant.Constant;
import cc.yugu.yhdw.common.domain.basic.Dept;
import cc.yugu.yhdw.common.domain.basic.Role;
import cc.yugu.yhdw.common.domain.basic.User;
import cc.yugu.yhdw.common.entity.json.ExtResult;
import cc.yugu.yhdw.common.entity.pagination.Page;
import cc.yugu.yhdw.common.utils.CodecUtils;
import cc.yugu.yhdw.webserver.config.AppConfig;
import cc.yugu.yhdw.webserver.constant.AppConstant;
import cc.yugu.yhdw.webserver.persistence.basic.AgentMapper;
import cc.yugu.yhdw.webserver.persistence.basic.DeptMapper;
import cc.yugu.yhdw.webserver.persistence.basic.RoleMapper;
import cc.yugu.yhdw.webserver.persistence.basic.UserMapper;
import cc.yugu.yhdw.webserver.persistence.hdw.AgencyMapper;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
/**
* 用户信息业务
* 
* @Param: 
* @Return: 
* @Author By: zjn 2018/7/5  15:47
*/ 
@Service
public class UserService {

    @Autowired
    AppConfig config;

    @Autowired
    RoleMapper roleMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    DeptMapper deptMapper;
    @Autowired
    AgentMapper agentMapper;
    @Autowired
    AgencyMapper agencyMapper;
    /**
    * 查询用户名
    * 
    * @Param: [id]
    * @Return: cc.yugu.yhdw.common.domain.basic.User
    * @Author By: zjn 2018/7/5  15:48
    */ 
    public User find(int id) {
        User user = userMapper.find(id);
        if (user.getAgentId() != null && user.getAgentId() != 0) {
            user.setAgentName(agentMapper.find(user.getAgentId())!=null?agentMapper.find(user.getAgentId()).getAgentName():"");
        }
        if (user.getAgencyId() != null && user.getAgencyId() != 0) {
            user.setAgencyName(agencyMapper.find(user.getAgencyId())!=null?agencyMapper.find(user.getAgencyId()).getAgencyName():"");
        }
        if (user.getDeptId() != null && user.getDeptId() != 0) {
            user.setDeptName(deptMapper.find(user.getDeptId())!=null?deptMapper.find(user.getDeptId()).getDeptName():"");
        }
        if (user.getRoleId() != null && user.getRoleId() != 0) {
            user.setRoleName(roleMapper.find(user.getRoleId())!=null?roleMapper.find(user.getRoleId()).getRoleName():"");
        }
        if (user.getType() != 0) {
            user.setTypeName(User.Type.getName(user.getType()));
        }
        return user;
    }
    /**
    * 根据运营商id查询
    * 
    * @Param: [agentId]
    * @Return: java.util.List<cc.yugu.yhdw.common.domain.basic.User>
    * @Author By: zjn 2018/7/5  15:48
    */ 
    public List<User> findByAgent(int agentId) {
        return userMapper.findByAgent(agentId);
    }
    /**
    * 注册时对新用户判断
    * 
    * @Param: [id, username]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/5  15:48
    */ 
    public ExtResult findUnique(Integer id, String username) {
        // 根据主键id和昵称精确查询，并返回行数,若行数为 0
        if (userMapper.findUnique(id, username) == 0) {
            return ExtResult.successResult();
        } else {
            return ExtResult.failResult("用户名重复");
        }
    }
    /**
    * 根据用户名和密码查询登录者信息
    * 
    * @Param: [username, password]
    * @Return: cc.yugu.yhdw.common.domain.basic.User
    * @Author By: zjn 2018/7/5  15:50
    */ 
    public User findByLoginInfo(String username, String password) {
        User data = new User();
        data.setUsername(username);
        data.setPassword(CodecUtils.password(password));
        User user = userMapper.findByLoginInfo(data);
        if (user!=null){
        if (user.getAgentId() != null && user.getAgentId() != 0) {
            user.setAgentName(agentMapper.find(user.getAgentId())!=null?agentMapper.find(user.getAgentId()).getAgentName():"");
        }
        if (user.getAgencyId() != null && user.getAgencyId() != 0) {
            user.setAgencyName(agencyMapper.find(user.getAgencyId())!=null?agencyMapper.find(user.getAgencyId()).getAgencyName():"");
        }
        if (user.getDeptId() != null && user.getDeptId() != 0) {
            user.setDeptName(deptMapper.find(user.getDeptId())!=null?deptMapper.find(user.getDeptId()).getDeptName():"");
        }
        if (user.getRoleId() != null && user.getRoleId() != 0) {
            user.setRoleName(roleMapper.find(user.getRoleId())!=null?roleMapper.find(user.getRoleId()).getRoleName():"");
        }
        if (user.getType() != 0) {
            user.setTypeName(User.Type.getName(user.getType()));
        }}
        return user;
    }
    /**
    * 根据主键更新最后登录时间
    * 
    * @Param: [id]
    * @Return: int
    * @Author By: zjn 2018/7/5  15:51
    */ 
    public int updateLoginTime(int id) {
        return userMapper.updateLoginTime(id, new Date());
    }
    /**
    * 分页查询
    * 
    * @Param: [user]
    * @Return: cc.yugu.yhdw.common.entity.pagination.Page
    * @Author By: zjn 2018/7/5  15:51
    */ 
    public Page findPage(User user) {
        user.setType(User.Type.PLATFORM.getValue());
        Page page = user.buildPage();
        page.setTotalItems(userMapper.findPageCount(user));
        user.setBeginIndex(page.getOffset());
        List<User> list = userMapper.findPageResult(user);
        for (User u : list) {
            if (u.getType() != 0) {
                u.setTypeName(User.Type.getName(u.getType()));
            }
        }
        page.setResult(list);
        return page;
    }
    /**
    * 新增用户
    * 
    * @Param: [user]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/5  15:52
    */ 
    @Transactional(rollbackFor = Throwable.class)
    public ExtResult create(User user) throws IOException {
        try {
            boolean usernameUnique = userMapper.findUnique(null, user.getUsername()) == 0;
            if (!usernameUnique) {
                return ExtResult.failResult("登录名已存在");
            }
            if (user.getDeptId() != null) {
                Dept dept = deptMapper.find(user.getDeptId());
                if (dept == null) {
                    return ExtResult.failResult("部门不存在");
                }
            }

            if (user.getRoleId() != null) {
                Role role = roleMapper.find(user.getRoleId());
                if (role == null) {
                    return ExtResult.failResult("角色不存在");
                }
            }
            if (user.getAgentId() == null && user.getAgencyId() == null && user.getSupplierId() != null) {
                user.setType(User.Type.SUPPLIER.getValue());
            } else if (user.getAgentId() != null && user.getAgencyId() != null && user.getSupplierId() == null) {
                user.setType(User.Type.AGENCY.getValue());
            } else if (user.getAgentId() != null && user.getAgencyId() == null && user.getSupplierId() == null) {
                user.setType(User.Type.AGENT.getValue());
            } else {
                return ExtResult.failResult("新增数据有误");
            }
            if (StringUtils.isEmpty(user.getPassword())) {
                user.setPassword(CodecUtils.password(Constant.DEFAULT_PASSWORD));
            } else {
                user.setPassword(CodecUtils.password(user.getPassword()));
            }

            if (StringUtils.isNotEmpty(user.getPortrait())) {
                File source = new File(user.getPortrait());
                if (source.exists()) {
                    File target = new File(config.portraitDir, source.getName());
                    FileUtils.copyFile(source, target);
                    user.setPortrait(AppConstant.PATH_PORTRAIT + target.getName());
                }
            }
            user.setCreateTime(new Date());
            userMapper.insert(user);
        } catch (IOException e) {
            return ExtResult.failResult("操作失败");
        }

        return ExtResult.successResult();
    }
    /**
    * 更新
    * 
    * @Param: [user]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/5  15:53
    */ 
    @Transactional(rollbackFor = Throwable.class)
    public ExtResult update(User user) throws IOException {
        try {
            boolean usernameUnique = userMapper.findUnique(user.getId(), user.getUsername()) ==0;
            if (!usernameUnique) {
                return ExtResult.failResult("登录名已存在");
            }

            if (user.getDeptId() != null) {
                Dept dept = deptMapper.find(user.getDeptId());
                if (dept == null) {
                    return ExtResult.failResult("部门不存在");
                }
            }

            if (user.getRoleId() != null) {
                Role role = roleMapper.find(user.getRoleId());
                if (role == null) {
                    return ExtResult.failResult("角色不存在");
                }
            }

            if (StringUtils.isEmpty(user.getPassword())) {
                user.setPassword(null);
            } else {
                user.setPassword(CodecUtils.password(user.getPassword()));
            }

            if (StringUtils.isNotEmpty(user.getPortrait()) && user.getPortrait().startsWith(AppConstant.PATH_TEMP)) {
                File source = new File(user.getPortrait());
                if (source.exists()) {
                    File target = new File(config.portraitDir, source.getName());
                    FileUtils.copyFile(source, target);
                    user.setPortrait(AppConstant.PATH_PORTRAIT + target.getName());
                }
            }
            if (user.getAgencyId() != null && user.getAgencyId() == 0) {
                user.setAgencyId(null);
            }
            userMapper.update(user);
        } catch (IOException e) {
            return ExtResult.failResult("操作失败");
        }

        return ExtResult.successResult();
    }
    /**
    * 根据主键和旧密码，更新新密码
    * 
    * @Param: [id, oldPassword, password]
    * @Return: int
    * @Author By: zjn 2018/7/5  15:53
    */ 
    public int updatePassword(int id, String oldPassword, String password) {
        return userMapper.updatePassword(id, oldPassword, password);
    }
    /**
    * 根据主键删除
    * 
    * @Param: [id]
    * @Return: cc.yugu.yhdw.common.entity.json.ExtResult
    * @Author By: zjn 2018/7/5  15:59
    */ 
    public ExtResult delete(int id) {
        try {
            userMapper.delete(id);
        } catch (Exception e) {
            return ExtResult.failResult("操作失败");
        }
        return ExtResult.successResult();
    }
}
